<?php

declare(strict_types=1);

namespace App\Common\Service;

use App\Setting\Service\SettingConfigService;
use Humx\HyperfSms\Contract\SmsInterface;
use Hyperf\Contract\ConfigInterface;
use Mine\Abstracts\AbstractService;
use Mine\Helper\Str;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

/**
 * 短信服务
 */
class SmsService extends AbstractService
{
    protected string $gateway = 'chuanglan';

    protected string $codeKey = 'ch_sms_login_code:';

    /**
     * 验证码应用场景
     * @var string
     */
    protected string $event;

    /**
     * @param string $event
     */
    public function __construct(string $event)
    {
        $this->event = $event;
    }


    /**
     * 发送手机验证码
     * @param string $mobile
     * @param $isTest
     * @return bool|string
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \RedisException
     */
    public function sendCode(string $mobile,$isTest = false): bool|string
    {
        if(empty($mobile)){
            return false;
        }

        $config = container()->get(SettingConfigService::class)->getConfigByKey("sms_sign");
        $signName = $config['value'] ?? '私域大师';
        container()->get(ConfigInterface::class)->set('sms.gateways.chuanglan.sign',"【{$signName}】");
        $easySms = container()->get(SmsInterface::class);
        $code = Str::random(6,1);

        $redis = redis();
        $content = "【{$signName}】您的验证码为: {$code}, 验证码将于五分钟后失效，请尽快操作。 如非本人操作, 请忽略本短信。";
        try {
            if(!$isTest){
                $easySms->send($mobile, [
                    'content' => $content
                ],[$this->gateway]);
            }
            $redis->set($this->event.$mobile,$code,300);
            return $code;
        } catch (InvalidArgumentException $e) {
            logger()->error('短信发送失败',[$e->getMessage()]);
            return false;
        } catch (NoGatewayAvailableException $e) {
            $errMsg = $e->getException($this->gateway)->getMessage();
            logger()->error('短信发送失败',[$errMsg]);
            return false;
        }
    }

    /**
     * 验证码验证
     * @param $mobile
     * @param $code
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \RedisException
     */
    public function verifyCode($mobile,$code): bool
    {
        $redis = redis();
        $redisCode = $redis->get($this->event.$mobile);
        if(empty($redisCode)){
            return false;
        }
         if($redisCode == $code){
             $redis->del($this->event.$mobile);
             return true;
         }
         return false;
    }
}